﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ParametersView.xaml.cs" company="R.V.Kasner">
//   Copyright © 2011 R.V.Kasner
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Owen.Terminal.View
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;

    using Owen.Terminal.ViewModel;

    /// <summary>
    ///   Логика взаимодействия для ParametersView.xaml
    /// </summary>
    public partial class ParametersView : IParametersView
    {
        private ListSortDirection lastDirection = ListSortDirection.Ascending;

        private GridViewColumnHeader lastHeaderClicked;

        private bool isSel;

        public ParametersView()
        {
            this.InitializeComponent();
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.SortListView(this.regModBesHeader.Tag as string, this.lastDirection);
            this.lastHeaderClicked = this.regModBesHeader;
        }

        public event Action Selected;

        public bool IsSelected
        {
            get
            {
                return this.isSel;
            }

            set
            {
                this.isSel = value;
                if (this.isSel) this.RaiseSelected();
            }
        }

        public string Title
        {
            get
            {
                return "Параметры";
            }
        }

        public IViewModel ViewModel
        {
            get
            {
                return this.DataContext as IViewModel;
            }

            set
            {
                this.DataContext = value;
            }
        }

        private void OnSortCollumn(object sender, RoutedEventArgs e)
        {
            var headerClicked = e.OriginalSource as GridViewColumnHeader;

            if (headerClicked != null)
            {
                if (headerClicked.Role != GridViewColumnHeaderRole.Padding)
                {
                    this.ApplyNewSort(headerClicked);
                }
            }
        }

        private void ApplyNewSort(GridViewColumnHeader headerClicked)
        {
            ListSortDirection direction;
            if (headerClicked != this.lastHeaderClicked) direction = ListSortDirection.Ascending;
            else
            {
                direction = this.lastDirection == ListSortDirection.Ascending 
                                ? ListSortDirection.Descending 
                                : ListSortDirection.Ascending;
            }

            var property = headerClicked.Tag as string;

            var isSorted = this.SortListView(property, direction);
            if (isSorted)
            {
                headerClicked.Column.HeaderTemplate = this.GetDirectionHeadedDataTemplate(direction);

                // Remove arrow from previously sorted header
                if (this.lastHeaderClicked != null && this.lastHeaderClicked != headerClicked) this.lastHeaderClicked.Column.HeaderTemplate = null;

                this.lastHeaderClicked = headerClicked;
                this.lastDirection = direction;
            }
        }

        private bool SortListView(string sortBy, ListSortDirection direction)
        {
            var dataView = CollectionViewSource.GetDefaultView(this.lv.ItemsSource);

            SortDescription? lastsort = null;
            if (dataView.SortDescriptions.Count > 0) lastsort = dataView.SortDescriptions[0];

            dataView.SortDescriptions.Clear();
            var sd = new SortDescription(sortBy, direction);
            try
            {
                dataView.SortDescriptions.Add(sd);
            }
            catch (InvalidOperationException)
            {
                dataView.SortDescriptions.Clear();
                if (lastsort != null) dataView.SortDescriptions.Add(lastsort.Value);
                return false;
            }

            dataView.Refresh();
            return true;
        }

        private DataTemplate GetDirectionHeadedDataTemplate(ListSortDirection direction)
        {
            return direction == ListSortDirection.Ascending
                       ? this.Resources["HeaderTemplateArrowDown"] as DataTemplate
                       : this.Resources["HeaderTemplateArrowUp"] as DataTemplate;
        }

        private void RaiseSelected()
        {
            var a = this.Selected;
            if (a != null) a();
        }

        private void TextBoxGotFocus(object sender, RoutedEventArgs e)
        {
            var tb = sender as TextBox;
            if (tb != null)
            {
                var lvi = tb.Tag as ListViewItem;
                if (lvi != null)
                {
                    lvi.IsSelected = true;
                }
            }
        }

        private void TextBoxLostFocus(object sender, RoutedEventArgs e)
        {
            var tb = sender as TextBox;
            if (tb != null)
            {
                var lvi = tb.Tag as ListViewItem;
                if (lvi != null)
                {
                    lvi.IsSelected = false;
                }
            }
        }
    }

    internal sealed class ValueTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            var element = container as FrameworkElement;

            if (element != null && item is ParameterViewModel)
            {
                var parameterViewModel = item as ParameterViewModel;

                if (parameterViewModel.Parameter.IsReadOnly) return element.FindResource("ValueReadOnlyTemp") as DataTemplate;
                else return element.FindResource("ValueTemp") as DataTemplate;
            }

            return null;
        }
    }
}